/**
 * Created with IntelliJ IDEA.
 * User: ajhin
 * Date: 9/13/13
 * Time: 8:46 AM
 * To change this template use File | Settings | File Templates.
 */
package com.societyGames.flashForms
{
import flash.display.DisplayObject;
import flash.display.Sprite;
import flash.events.Event;
import flash.text.TextField;
import flash.text.TextLineMetrics;

public class CenterScaleTextFieldContainer extends Sprite
{
  private var _textField:TextField;
  private var _mainContainer:DisplayObject;
  private var _centerScaleContainer:CenterScaleContainer;

  public function CenterScaleTextFieldContainer()
  {
    this._centerScaleContainer = new CenterScaleContainer();
    this._mainContainer = _centerScaleContainer;
    this.addChild(this._mainContainer);
  }

  public function set textField(newTextField:TextField):void
  {
    var dynamicTextField:DynamicTextField = _textField as DynamicTextField;
    if (dynamicTextField != null)
    {
      dynamicTextField.sizeChangedEventObject.removeEventListener(textFieldSizeChangedHandler);
    }

    this._textField = newTextField;

    dynamicTextField = _textField as DynamicTextField;
    if (dynamicTextField != null)
    {
      dynamicTextField.sizeChangedEventObject.addEventListener(textFieldSizeChangedHandler);
    }

    recalculate();
  }

  public function get textField():TextField
  {
    return this._textField;
  }

  private function textFieldSizeChangedHandler(event:Event):void
  {
    recalculate();
  }

  private function recalculate():void
  {
    var width:Number = 0;
    for (var lineIndex:int = 0; lineIndex < _textField.numLines; lineIndex++)
    {
      //Calculate the max size
      var metrics:TextLineMetrics = _textField.getLineMetrics(lineIndex);
      if (metrics.width > width)
      {
        width = metrics.width;
      }
    }
    _textField.width = width + 6;
    _textField.height = _textField.numLines * _textField.textHeight + 4;
    _centerScaleContainer.item = _textField;
  }

  public override function set width(value:Number):void
  {
    this._mainContainer.width = value;
  }

  public override function set height(value:Number):void
  {
    this._mainContainer.height = value;
  }
}
}
